package ifosup.chat.metier;

import ifosup.chat.common.IMessageListener;
import ifosup.chat.common.ISenderMessage;
import ifosup.chat.common.Message;
import ifosup.chat.common.Utilisateur;
import ifosup.chat.swing.IhmConversation;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Client implements ISenderMessage,Runnable {
	
	
	private Socket clientSocket;
	private Utilisateur contact;
	private ObjectOutputStream out;
	IMessageListener messageListener;
	
	private ObjectInputStream in;
	
	
	public Client(Utilisateur _contact,IMessageListener messageListener) {
		this.contact = _contact;		
		this.messageListener = messageListener;
		try {
			clientSocket = new Socket(contact.getIp(), 4444);
			this.activate();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public Client(Socket s) {
		this.clientSocket = s;
		try {
			this.activate();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void activate() throws IOException {
		this.out = new ObjectOutputStream(this.clientSocket.getOutputStream());
		this.in = new ObjectInputStream(this.clientSocket.getInputStream());
		Thread t = new Thread(this);
		t.start();
	}

	@Override
	public void sendMessage(Message message) {
		try {
			this.out.writeObject(message);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		
		try {
			Message message;
			while( (message = (Message) this.in.readObject()) != null){
				System.out.println(" Client message received :"+message);
				if (this.messageListener == null){
					this.messageListener = new IhmConversation(message.getEmetteur(), message.getDestinataire(),this);
					System.out.println("yo :"+message.getDestinataire());
				}
				this.messageListener.receiveMessage(message);
			
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public IMessageListener getMessageListener() {
		return messageListener;
	}

	public void setMessageListener(IMessageListener messageListener) {
		this.messageListener = messageListener;
	}
	
	
	
}
